﻿using System;
using UnityEngine.UI;

namespace BToolkit.ExeUtils
{
    public class EditSlider
    {
        Slider slider;
        string storageKey;
        float currValue, oldValue;

        public static void Create(Slider slider, string key, float sliderMin, float sliderMax, float defaultValue, Action<float> onSliderEdit)
        {
            new EditSlider(slider, key, sliderMin, sliderMax, defaultValue, onSliderEdit);
        }

        private EditSlider(Slider slider, string key, float sliderMin, float sliderMax, float defaultValue, Action<float> onSliderEdit)
        {
            this.slider = slider;
            this.storageKey = key;
            this.slider.minValue = sliderMin;
            this.slider.maxValue = sliderMax;
            this.currValue = DataStorage.GetFloat(storageKey, defaultValue);
            this.slider.value = this.currValue;
            this.slider.onValueChanged.RemoveAllListeners();
            this.slider.onValueChanged.AddListener((float v) =>
            {
                if (onSliderEdit != null) onSliderEdit(v);
                this.currValue = v;
            });
            if (onSliderEdit != null) onSliderEdit(this.currValue);
            MainController.onEditModeEnable += (bool b, bool save) =>
            {
                if (b)
                {
                    this.currValue = DataStorage.GetFloat(storageKey, defaultValue);
                    slider.value = this.currValue;
                    this.oldValue = this.currValue;
                }
                else
                {
                    if (save)
                    {
                        DataStorage.SetFloat(storageKey, this.currValue);
                    }
                    else
                    {
                        slider.value = this.oldValue;
                    }
                }
            };
        }

    }
}